package com.fzy.servlet;

import org.w3c.dom.ls.LSOutput;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/newsList")
public class NewsListServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String DB_URL = "jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=utf-8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "13100140892Fzy!";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");
        // 加载MySQL JDBC驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try (
                Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM news_table")) {

            out.println("<html><body>");
            // 添加一些简单的CSS样式，让表格更好看
            out.println("<style>");
            out.println("table {border-collapse: collapse; width: 100%;}");
            out.println("th, td {border: 1px solid #ddd; padding: 8px; text-align: left;}");
            out.println("th {background-color: #f2f2f2;}");
            out.println("</style>");
            out.println("<table>");
            out.println("<tr><th>标题</th><th>作者</th><th>日期</th><th>热度</th><th>操作</th></tr>");
            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                String author = rs.getString("author");
                String date = rs.getString("date");
                int heat = rs.getInt("heat");

                out.println("<tr><td>" + title + "</td><td>" + author + "</td><td>" + date + "</td><td>" + heat + "</td><td><a href='DeleteNewsServlet?id=" + id + "'>删除</a>  <a href='UpdateNewsServlet?id=" + id + "'>修改</a></td></tr>");
            }
            out.println("</table>");
            out.println("</body></html>");

        } catch (SQLException e) {
            e.printStackTrace();
            out.println("数据库连接或查询出错: " + e.getMessage());
        }
    }
}